package com.trace.meat.interceptor;

import com.alibaba.fastjson.JSON;
import com.trace.meat.config.ParameterServletRequestWrapper;
import com.trace.meat.entity.AdminAcct;
import com.trace.meat.entity.Ent;
import com.trace.meat.entity.Result;
import com.trace.meat.service.AdminAcctService;
import com.trace.meat.service.EntService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Component
public class TokenInterceptor implements HandlerInterceptor
{

    private Logger logger=LoggerFactory.getLogger(TokenInterceptor.class);
    /**
     * 忽略拦截的url
     */
    private String urls[] = {
            "/ent/login",
            "/ent/register",
            "/admin/login",
            "/admin/register"
    };
    @Autowired
    private EntService entService;
    @Autowired
    private AdminAcctService adminAcctService;
    /**
     * 进入controller层之前拦截请求
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
        Map<String, String[]> parameterMap = new HashMap<>(request.getParameterMap());
        parameterMap.put("eid",new String[]{"1"});
        ParameterServletRequestWrapper parameterServletRequestWrapper=new ParameterServletRequestWrapper(request,parameterMap);
        String url = request.getRequestURI();
        String token = request.getHeader("token");
        String method = request.getMethod();
        if (!method.equals("OPTIONS")){
            logger.info(token);
            logger.info(url);
            logger.info(method);
            // 遍历需要忽略拦截的路径
            for (String item : this.urls){
                if (item.equals(url)){
                    return true;
                }
            }
            // 查询验证token
            boolean flag=false;
            if(url.startsWith("/admin")) {
                AdminAcct adminAcct=adminAcctService.queryByToken(token);
                if(adminAcct==null){
                    flag=true;
                }
                else {
                    System.out.println("id:" + String.valueOf(adminAcct.getId()));
                }
            }
            else if(url.startsWith("/ent")){
                Ent ent=entService.queryByToken(token);
                if(ent==null){
                    flag=true;
                }
                else {
                System.out.println("eid:"+String.valueOf(ent.getEid())); }
            }

            if (flag){
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json; charset=utf-8");
                PrintWriter out = null ;
                try{
                    Result res = new Result();
                    res.setMsg("token验证失败,登录失败");
                    res.setSuccess(false);
                    String json = JSON.toJSONString(res);
                    response.setContentType("application/json");
                    out = response.getWriter();
                    // 返回json信息给前端
                    out.append(json);
                    out.flush();
                    return false;
                } catch (Exception e){
                    e.printStackTrace();
                    response.sendError(500);
                    return false;
                }
            }
            return true;
        }
        return true;
    }

}
